package com.suyundeng.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suyundeng.entity.JsonResult;
import com.suyundeng.entity.SRole;
import com.suyundeng.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @ResponseBody
    @GetMapping("/roles")
    public JsonResult getPage(@RequestParam(value = "current",required = false,defaultValue = "1")Integer current){
        Page<SRole> page = new Page<>(current,10);
        try{
            IPage<SRole> data = roleService.getPage(page);
            return new JsonResult(1,"ok",data);
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(0,"error",null);
        }
    }

    @ResponseBody
    @GetMapping("/getRoles")
    public JsonResult getRoles(){
        try{
            List<SRole> data = roleService.list();
            return new JsonResult(1,"ok",data);
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(0,"error",null);
        }
    }

    @ResponseBody
    @GetMapping("/role")
    public JsonResult getRolesByUserId(@RequestParam("userId") String userId){
        try{
            List<SRole> data = roleService.selectRolesByUserId(userId);
            return new JsonResult(1,"ok",data);
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(0,"error",null);
        }
    }

    @ResponseBody
    @DeleteMapping("/role/{id}")
    public JsonResult deleteRole(@PathVariable("id")String id){
        try{
            boolean data = roleService.removeById(id);
            return new JsonResult(1,"ok",data);
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(0,"error",null);
        }
    }

    @ResponseBody
    @PostMapping("/role")
    public JsonResult addRole(@RequestBody SRole role){
        try{
            boolean data = roleService.save(role);
            return new JsonResult(1,"ok",data);
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(0,"error",null);
        }
    }

    @ResponseBody
    @PutMapping("/role")
    public JsonResult modifyRole(@RequestBody SRole role){
        try{
            boolean data = roleService.updateById(role);
            return new JsonResult(1,"ok",data);
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(0,"error",null);
        }
    }
}
